package com.thuanhoang.boo;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import slidingmenu.lib.SlidingMenu;
import util.Constant;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;

import com.boo.service.SendDataService;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.origamilabs.library.views.StaggeredGridView;
import com.thuanhoang.boo.adapter.MenuCategoryAdapter;
import com.thuanhoang.boo.adapter.ProductListAdapter;
import com.thuanhoang.boo.model.Merchant;
import com.thuanhoang.boo.model.ObjGroupCategoryItem;
import com.thuanhoang.boo.model.ObjMerchantCategory;
import com.thuanhoang.boo.model.Product;

public class ProductListActivity  extends Activity{
	public SlidingMenu slideMenu;
	static Merchant merchant;
	private ArrayList<Product> listProduct;
	private ArrayList<Product> listProductSearch;
	private ArrayList<ObjMerchantCategory>listCategori;
	private ArrayList<ObjGroupCategoryItem> listGroup;
	private StaggeredGridView gridView;
	public TextView txtHintSearch;
	public boolean showsearch = false;
	View regionSearch;
	View btnSearch;
	public EditText txtsearch;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_product_view);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText(ProductListActivity.merchant.getMerchName());
		listProduct = new ArrayList<Product>();
		listCategori = new ArrayList<ObjMerchantCategory>();
		listGroup = new ArrayList<ObjGroupCategoryItem>();
		gridView =(StaggeredGridView) findViewById(R.id.gridView);
		gridView.setItemMargin(10);
		gridView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
			}
		});
		gridView.setOnItemClickListener(new com.origamilabs.library.views.StaggeredGridView.OnItemClickListener() {
			@Override
			public void onItemClick(StaggeredGridView parent, View view, int position,
			        long id) {
				Product member = listProductSearch.get(position);
				ProductDetailActivity.product = member;
				Intent intent = new Intent(ProductListActivity.this,ProductDetailActivity.class);
				startActivity(intent);

			}
		});
		initAction();		
		showLoading();
		getCategori();
		getData();		
	}
	
	private void initAction() {
		View backButton = (View) findViewById(R.id.btn_back);
		backButton.setOnClickListener( new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		View btnAccount = (View)findViewById(R.id.btn_account);
		btnAccount.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(ProductListActivity.this, UpdateInfoActivity.class));
			}
		});
		// TODO Auto-generated method stub
		
	}

	protected void openDialogListCategory() {
		
		LayoutInflater inflater = getLayoutInflater();
		View alertView = inflater.inflate(R.layout.menu_category,null);
		ExpandableListView listDetails = (ExpandableListView) alertView.findViewById(R.id.listCategory);
		// create adapter
		MenuCategoryAdapter listAdapter = new MenuCategoryAdapter(this,listGroup);
		// setting list adapter
		listDetails.setAdapter(listAdapter);
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Chọn danh mục");
		builder.setView(alertView);
		final AlertDialog alert = builder.create();
		listDetails.setOnChildClickListener(new OnChildClickListener() {    
	        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,int childPosition,long id) {
	        	updateData(listGroup.get(groupPosition).getListChild().get(childPosition).getProductMerchCatId());
	        	alert.dismiss();
	            return false;
	        }
	    });
		
		listDetails.setOnGroupClickListener(new OnGroupClickListener() {
			
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
					long id) {
				if(groupPosition==0){
					updateData("0");
					alert.dismiss();
				}
				else{
					//updateData(listGroup.get(groupPosition).getGroupItem().getProductMerchCatId());
//					alert.dismiss();
				}
				// TODO Auto-generated method stub
				return false;
			}
		});
		
		// set expandList
		if(listGroup.size()>1){
			for (int position =1; position < listGroup.size(); position++) {
				listDetails.expandGroup(position);
			}
		}		
		//String [] mcategory = listCategori.toArray() 
		
		alert.show();
	}
	public void createListgroup(){
		listGroup = new ArrayList<ObjGroupCategoryItem>();
		ObjGroupCategoryItem allgroupitem = new ObjGroupCategoryItem();
		ArrayList<ObjMerchantCategory> category = new ArrayList<ObjMerchantCategory>();
		ObjMerchantCategory group = new ObjMerchantCategory();
		group.setProductMerchCatName("Tất cả");
		group.setProductMerchCatId("0");
		allgroupitem.setGroupItem(group);
		allgroupitem.setListChild(category);
		listGroup.add(allgroupitem);
		for(int i = 0; i < listCategori.size();i++){
			
			if(listCategori.get(i).getCatParent() == listCategori.get(i).getProductMerchCatId()){
				ObjGroupCategoryItem groupitem = new ObjGroupCategoryItem();
				groupitem.setGroupItem(listCategori.get(i));
				ArrayList<ObjMerchantCategory> listchild = new ArrayList<ObjMerchantCategory>();
				for(int j = 0; j <listCategori.size(); j++){
					if((i!=j) &&(listCategori.get(j).getCatParent().equals(listCategori.get(i).getProductMerchCatId()))){
						listchild.add(listCategori.get(j));
					}
				}
				groupitem.setListChild(listchild);
				listGroup.add(groupitem);
			}
		}
		
	}
	
	public void initButton(){
		View btnMenu = findViewById(R.id.menu_header);
	btnMenu.setOnClickListener( new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			openDialogListCategory();
			// TODO Auto-generated method stub
			
		}
	});
	btnSearch =(View) findViewById(R.id.button_search);
	txtsearch = (EditText) findViewById(R.id.search_text);
	txtHintSearch = (TextView) findViewById(R.id.header_hint_txt);
	 regionSearch = (View) findViewById(R.id.search_header);
	regionSearch.setOnClickListener( new View.OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			if (!showsearch) {
				btnSearch.setBackgroundResource(R.drawable.cancel_button_selector);
				txtsearch.setVisibility(View.VISIBLE);
				txtHintSearch.setVisibility(View.VISIBLE);
				txtsearch.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.showSoftInput(txtsearch, 0);
			} else {
				btnSearch.setBackgroundResource(R.drawable.search_button_selector);
				txtsearch.setText("");
				txtsearch.setVisibility(View.GONE);
				txtHintSearch.setVisibility(View.GONE);
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(txtsearch.getWindowToken(), 0);
			}
			showsearch = !showsearch;
			// TODO Auto-generated method stub
			
		}
	});
	}
	
	
	public void showLoading() {
		findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
	}

	public void hiddenLoading() {
		findViewById(R.id.loadingPanel).setVisibility(View.GONE);
	}
	
	private void getData() {
		// get data friend from server ?merchId=
		try{
			final SendDataService service  = new SendDataService(this);
			JSONObject jsonparams = new JSONObject();
			jsonparams.put("merchId", ProductListActivity.merchant.getMerchId());
			service.sendData(Constant.API_GET_PRODUCT_URL, jsonparams, new JsonHttpResponseHandler() {
				@Override
				public void onSuccess(JSONObject response) {		
					try {
						JSONArray listPro = response.getJSONArray("Products");
						if(listPro!=null){
							Gson gson = new Gson();
							for (int i = 0; i < listPro.length(); i ++){
								JSONObject memberJsonInfo = listPro.getJSONObject(i);
								String stringInfo = memberJsonInfo.toString();
								Product newPro = gson.fromJson(stringInfo, Product.class);
								listProduct.add(newPro);					
							}
							updateData("0");
						}
					} catch (Exception e) {
						// TODO: handle exception
					}
				}

				@Override
				public void onFailure(Throwable error) {
					Log.d("failure", "is " + error.getMessage());
					error.printStackTrace();
				}
			});
		}
		catch (Exception e){
		}
			
		}

	public void getCategori(){
		try{
			final SendDataService service  = new SendDataService(this);
			JSONObject jsonparams = new JSONObject();
			jsonparams.put("merchId", ProductListActivity.merchant.getMerchId());
			service.sendData(Constant.API_GET_CATEGORY_API, jsonparams,
					new JsonHttpResponseHandler() {
						@Override
						public void onSuccess(JSONObject response) {
							try {
							JSONArray listPro = response.getJSONArray("MerchantCategories");
							if(listPro!=null){
								Gson gson = new Gson();
								for (int i = 0; i < listPro.length(); i ++){
									JSONObject memberJsonInfo = listPro.getJSONObject(i);
									String stringInfo = memberJsonInfo.toString();
									ObjMerchantCategory newCategori = gson.fromJson(stringInfo, ObjMerchantCategory.class);
									listCategori.add(newCategori);					
								}
								createListgroup();
								initButton();
								//configureSlideMenu();
							}
							} catch (Exception e) {
								// TODO: handle exception
							}
						}

						@Override
						public void onFailure(Throwable error) {
							
						}
					});
		}
		catch(Exception e){
			
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}


	public void updateData(String categoryId){
		if(categoryId.equalsIgnoreCase("0")){
			listProductSearch = listProduct;
		}
		else{
			listProductSearch = new ArrayList<Product>();
			for(int i = 0 ; i <listProduct.size() ; i++){
				Product proitem = listProduct.get(i);
				if(proitem.getProductMerchCatId().equalsIgnoreCase(categoryId)){
					listProductSearch.add(proitem);
				}
			}
		}
		ProductListAdapter productAdapter = new ProductListAdapter(ProductListActivity.this, listProductSearch );
		gridView.setAdapter(productAdapter);
		hiddenLoading();
	}

	

}
